/**@module 项目资源模块 */

import axios from 'axios'
import co from 'co'
import qs from 'qs'

/**
 * 应用服务器地址
 */
axios.defaults.baseURL = 'http://14.215.50.212:8888';
/**
 * 环境适配
 */
const env = process.env.NODE_ENV;
let static_pic = void 0;
let thumbnail = void 0;
if(env === 'production') {
  static_pic = '/static_pic';
  thumbnail = '/static_pic/thumbnail';
  // axios.defaults.baseURL = 'http://127.0.0.1:8888';
} else {// development
  static_pic = '/static';
  thumbnail = '/static/thumbnail';
  // axios.defaults.baseURL = 'http://14.215.50.212:8888';
}

/**
 * 屏幕宽度变量
 */
const MOBILE_WIDTH = 740;// 移动端尺寸



/**
 * 设置拦截
 * 一般用于token验证，现在不需要
 */
// axios.interceptors.response.use(response => response, err => Promise.reject(err));


/**
 * @method
 * @description - 自定义封装axios.post
 * 1. 处理webservice交互出现的{"d":null}问题
 * 1. 自定义reject的位置及信息
 * 1. 返回100%正确的response
 * 
 * @param {请求地址} url
 * @param {请求参数} params
 */
const dgpost = (url, params) => {
  params = qs.stringify(params);
  return new Promise((resolve, reject) => {
    axios.post(url, params,
    {
      headers: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    }).then(response => {

      let {// 接收response所有属性
        data, status, statusText, header, config
      } = response;

      if(status === 200) {
        if(typeof data === 'string') {// 如果是字符串
          try {
            data = JSON.parse(data.replace(/\{"d":\s?null\}|\n|\r|\s/g, ''));
          } catch (err) {
            console.error('json字符串解析错误：', {err, url, params, data});
            reject({msg: (err || 'json字符串解析错误')});
          }
        }
        data.result = +data.result;// 保证result为number类型
        if(data.result !== 1) {
          console.error('result不等于1：', {url, params, data});
          reject({msg: (data.msg || 'result不等于1')});
        }
      } else {
        console.error('请求不被接收：', {url, params, response});
        reject({msg: (status || '请求不被接收')});
      }

      // 100%有用的response
      resolve({data, status, statusText, header, config});
    }).catch(err=> {
      console.error('axios.post错误：', {err, url, params});
      reject({msg: (err || 'error~~')});
    });
  });
}


export default {
  install(Vue, options) {
    Vue.prototype.$http = axios;
    Vue.prototype.dgpost = dgpost;
    Vue.prototype.co = co;
    Vue.prototype.static_pic = static_pic;
    Vue.prototype.thumbnail = thumbnail;
    Vue.prototype.MOBILE_WIDTH = MOBILE_WIDTH;
  }
}